<script setup>
import { useUserStore } from '@/stores/user';
import JWeixin from 'weixin-js-sdk';
import { Toast } from 'vant';
import { queryUrlParam } from '@/utils/tools';
import { EiInfo } from '@eplat/ei';
// 调用4j的service
import api4j from '@/api/example';

const router = useRouter();
const user = useUserStore();
const loading = ref(false);
const finish = ref(false);

// 授权
JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
      'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
      api4j.APPID +
      '&redirect_uri=https%3A%2F%2F' +
      api4j.SERVER_DOMAIN +
      '%2F%23%2FWX%2FWD%2FWXWD06&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    if (user.getToken == '' || user.getToken == undefined) {
      // Toast('正在授权');
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogin(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          // Toast(res.msg);
          window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            api4j.APPID +
            '&redirect_uri=https%3A%2F%2F' +
            api4j.SERVER_DOMAIN +
            '%2F%23%2FWX%2FWD%2FWXWD06&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        // Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
          res.extAttr.token,
          res.extAttr.userInfo.attrs.headimgurl,
          res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);

        onLoad();
      });
    }
  }
});

const onLoad = async () => {
  loading.value = true;
  applyList();
  loading.value = false;
};

const applyList = async () => {
  username.value = user.getUsername.trim();
  phone.value = user.getPhone.trim();
};
const onSubmit = async () => {
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken.trim());
  postEiInfo.set('userName', username.value);
  postEiInfo.set('phone', phone.value);
  postEiInfo.set('code', sms.value);

  await api4j.RCRM0103_infoUpdate(postEiInfo).then((res) => {
    Toast(res.msg);
    if (res.status == 1) {
      // 修改成功set
      user.setUserNameTel(username.value, phone.value);
      router.push('/WX/WD/WXWD02');
    }
  });
};
const submit = async () => {
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken.trim());
  postEiInfo.set('userName', username.value);
  postEiInfo.set('phone', phone.value);
  postEiInfo.set('code', sms.value);

  await api4j.RCRM0103_infoUpdate(postEiInfo).then((res) => {
    Toast(res.msg);
    if (res.status == 1) {
      // 修改成功set
      user.setUserNameTel(username.value, phone.value);
      router.push('/WX/WD/WXWD02');
    }
  });
};

const gainCode = async () => {
  if (isClick.value) {
    if (
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
        phone.value
      )
    ) {
      // 获取验证码接口
      const postEiInfo = new EiInfo();
      postEiInfo.set('phone', phone.value);
      await api4j.RCRM0103_yzm(postEiInfo).then((res) => {
        Toast(res.msg);
      });
      isClick.value = false;
      let s = 60;
      time.value = s + 's';
      const interval = setInterval(() => {
        s--;
        time.value = s + 's';
        if (s < 0) {
          time.value = '重新获取';
          isClick.value = true;
          clearInterval(interval);
        }
      }, 1000);
    } else {
      Toast.fail('请输入正确的手机号码');
    }
  }
};

const username = ref('');
const phone = ref('');
const sms = ref('');
const time = ref('获取验证码');
const isClick = ref(true);
</script>
<template>
  <van-list
    v-model:loading="loading"
    class="working-list"
    :finished="finish"
    finished-text=""
    offset="1"
    @load="onLoad"
  >
    <div
      style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #4b75e5;
        height: 65px;
        color: white;
        z-index: 1000;
      "
    >
      <div style="font-size: 20px; padding-top: 20px; text-align: center">修改信息</div>
      <van-button
        to="/WX/WD/WXWD02"
        style="
          background-color: #4b75e5;
          color: white;
          display: flex;
          flex-direction: column;
          align-items: center;
          border: 1px solid #4b75e5;
          margin-top: -32px;
          margin-left: 20px;
        "
      >
        <img
          src="@/assets/tb166.svg"
          style="width: 35px; height: 35px; margin-left: -20px; margin-top: 3px"
          alt=""
        />
      </van-button>
    </div>
    <div style="margin-top: 75px">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            required
            name="姓名"
            label="姓名"
            placeholder="姓名"
            :rules="[
              { required: true, message: '请填写姓名' },
              { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: '姓名格式不正确' }
            ]"
          />
          <van-field
            v-model="phone"
            required
            type="tel"
            name="手机号"
            label="手机号"
            placeholder="手机号"
            :rules="[
              { required: true, message: '请填写手机号' },
              { pattern: /^1\d{10}$/, message: '手机号格式不正确' }
            ]"
          />

          <van-field
            v-model="sms"
            center
            required
            type="tel"
            name="验证码"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[
              { required: true, message: '请输入验证码' },
              { pattern: /^\d{6}$/, message: '验证码格式不正确' }
            ]"
            use-button-slot
          >
            <template #button>
              <van-button native-type="button" size="small" type="primary" @click="gainCode">{{
                time
              }}</van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button
            round
            block
            style="background-color: #4b75e5; color: white"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
<!--      <van-button round block style="background-color: #4b75e5; color: white" @click="submit()">-->
<!--        发送推送信息-->
<!--      </van-button>-->
    </div>
  </van-list>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
